<?php
namespace app\mingteng\controller;

use think\AjaxPage;
use think\Db;
use think\Loader;

class User extends Base{

    public $listRows = 20;

    public function _initialize(){
        parent::_initialize();
        $this->assign('userSex', config('userSex'));
        $this->assign('couponType', config('couponType'));
        $this->assign('couponStatus', config('couponStatus'));
    }

    //会员等级
    public function grade(){
        return $this->fetch();
    }

    public function ajax_grade(){
        $params = input('post.');
        $page = input('page', 1);

        $where = array();
        $where['gradeIsDel'] = ['=', '0'];
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            $where['gradeName'] = ['like', '%'.$params['keywords'].'%'];
        }

        $count = Db::name('user_grade')->where($where)->count();
        $list = Db::name('user_grade')->where($where)->page($page, $this->listRows)->select();
        $this->assign('list', $list);

        $ajaxPage = new AjaxPage($count, $this->listRows);
        $show = $ajaxPage->show();
        $this->assign('page', $show);

        return $this->fetch();
    }

    public function gradeAdd(){
        return $this->fetch('grade_add');
    }

    public function doGradeAdd(){
        $params = input('post.');

        if (empty($params['gradeName'])) {
            return json(array('code' => 500, 'msg' => '请填写等级名称'));
        }
        if (empty($params['validMonth'])) {
            return json(array('code' => 500, 'msg' => '请填写购买有效期'));
        }
        if (empty($params['gradePrice'])) {
            return json(array('code' => 500, 'msg' => '请填写购买价格'));
        }
        if (empty($params['gradeDiscount'])) {
            return json(array('code' => 500, 'msg' => '请填写等级折扣'));
        }

        $catch = array(
            'gradeSort' => $params['gradeSort'],
            'gradeName' => $params['gradeName'],
            'validMonth' => $params['validMonth'],
            'gradePrice' => $params['gradePrice'],
            'gradeImg' => !empty($params['gradeImg']) ? config('site_url.site_url') . $params['gradeImg'] : false,
            'gradeContent' => !empty($params['gradeContent']) ? $params['gradeContent'] : false,
            'gradeDiscount' => $params['gradeDiscount'],
            'reservationDiscount' => $params['reservationDiscount'],
        );
        $gradeId = Db::name('user_grade')->insertGetId($catch);
        if ($gradeId > 0) {
            return json(array('code' => 200, 'msg' => '添加成功'));
        }else{
            return json(array('code' => 500, 'msg' => '数据添加出错，请联系管理员'));
        }
    }

    public function gradeEdit(){
        $gradeId = input('gradeId');

        $detail = Db::name('user_grade')->where('gradeId', '=', $gradeId)->find();
        $this->assign('detail', $detail);

        return $this->fetch('grade_edit');
    }

    public function doGradeEdit(){
        $params = input('post.');

        if (empty($params['gradeName'])) {
            return json(array('code' => 500, 'msg' => '请填写等级名称'));
        }
        if (empty($params['validMonth'])) {
            return json(array('code' => 500, 'msg' => '请填写购买有效期'));
        }
        if (empty($params['gradePrice'])) {
            return json(array('code' => 500, 'msg' => '请填写购买价格'));
        }
        if (empty($params['gradeDiscount'])) {
            return json(array('code' => 500, 'msg' => '请填写等级折扣'));
        }

        if (!empty($params['gradeImg'])) {
            $params['gradeImg'] = strstr($params['gradeImg'],"public");
        }

        $catch = array(
            'gradeSort' => $params['gradeSort'],
            'gradeName' => $params['gradeName'],
            'validMonth' => $params['validMonth'],
            'gradePrice' => $params['gradePrice'],
            'gradeImg' => !empty($params['gradeImg']) ? config('site_url.site_url') . "/" . $params['gradeImg'] : false,
            'gradeContent' => !empty($params['gradeContent']) ? $params['gradeContent'] : false,
            'gradeDiscount' => $params['gradeDiscount'],
            'reservationDiscount' => $params['reservationDiscount'],
        );
        Db::name('user_grade')->where('gradeId', '=', $params['gradeId'])->save($catch);
        return json(array('code' => 200, 'msg' => '编辑成功'));
    }

    public function gradeDel(){
        $params = input('post.');

        Db::name('user_grade')->where('gradeId', '=', $params['del_id'])->save(array(
            'gradeIsDel' => '1',
        ));
        return json(array(
            'code' => 200,
            'msg' => '操作成功',
        ));
    }

    //会员管理
    public function user(){
        $grade = Db::name('user_grade')->where('gradeIsDel', '=', '0')->select();

        $userId = Db::name('user')->where('gradeId','in',[1,2])->where('gradeEndTime','<',time())->column('userId');
        Db::name('user')->where('userId','in',$userId)->update(['gradeId'=>0,'gradeName'=>'']);
        $this->assign('grade', $grade);

        return $this->fetch();
    }

    public function ajax_user(){
        $params = input('post.');
        $page = input('page', 1);

        $where = array();
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            $where['nickName|userMobile'] = array('like', '%'.$params['keywords'].'%');
        }
        if (isset($params['gradeId']) && $params['gradeId'] != '') {
            $where['gradeId'] = array('=', $params['gradeId']);
        }
        if (isset($params['userStatus']) && $params['userStatus'] != '') {
            $where['userStatus'] = array('=', $params['userStatus']);
        }
        if (isset($params['userRole']) && $params['userRole'] != '') {
            $where['role'] = array('=', $params['userRole']);
        }
        $count = Db::name('user')->where($where)->count();
        $list = Db::name('user')->where($where)->page($page, $this->listRows)->order('addTime desc')->select();
        $this->assign('list', $list);

        $ajaxPage = new AjaxPage($count, $this->listRows);
        $show = $ajaxPage->show();
        $this->assign('page', $show);

        return $this->fetch();
    }

    public function userEdit(){
        $userId = input('userId');

        $userInfo = Db::name('user')->where('userId', '=', $userId)->find();
        $this->assign('userInfo', $userInfo);

        return $this->fetch('user_edit');
    }

    public function rankAdd(){
        $userId = input('userId');

        $userInfo = Db::name('user')->where('userId', '=', $userId)->find();
        $this->assign('userInfo', $userInfo);

        $rankCount = Db::name('rank')->where('userId', '=', $userId)->order('addTime desc')->select();
        $this->assign('randCount', $rankCount);

        return $this->fetch('rank_add');
    }

    public function doRankAdd(){
        $params = input('post.');

        if (empty($params['count'])) {
            return json(array('code' => 500, 'msg' => '请填写杆数'));
        }
        if ($params['count'] <= 0) {
            return json(array('code' => 500, 'msg' => '请填写正确的杆数数字'));
        }
        if (empty($params['addTime'])) {
            return json(array('code' => 500, 'msg' => '请选择成绩的获得时间'));
        }

        $catch = array(
            'userId' => $params['userId'],
            'count' => $params['count'],
            'addTime' => strtotime($params['addTime']),
        );
        $rankId = Db::name('rank')->insertGetId($catch);
        return json(array('code' => 200, 'msg' => '添加成功'));
    }

    public function rankDel(){
        $del_id = input('del_id');

        Db::name('rank')->where('rankId', '=', $del_id)->delete();
        return json(array('code' => 200, 'msg' => '操作成功'));
    }


    public function userDel(){
        $del_id = input('del_id');

        Db::name('user')->where('userId', '=', $del_id)->save(array(
            'userStatus' => 0,
        ));
        return json(array('code' => 200, 'msg' => '操作成功'));
    }

    public function userGradeEdit(){
        $userId = input('userId');

        $userInfo = Db::name('user')->where('userId', '=', $userId)->find();
        $this->assign('userInfo', $userInfo);
        $grade = Db::name('user_grade')->where('gradeIsDel', '=', '0')->select();
        $this->assign('grade', $grade);

        return $this->fetch('user_grade_edit');
    }

    public function doUserGradeEdit(){
        $params = input('post.');

        if (empty($params['gradeId'])) {
            return json(array('code' => 500, 'msg' => '请选择要开通的会员等级'));
        }
        if (empty($params['gradeEndTime'])) {
            return json(array('code' => 500, 'msg' => '请选择本次开通的到期时间'));
        }

        $grade = Db::name('user_grade')->where('gradeId', '=', $params['gradeId'])->find();
        if (empty($grade)) {
            return json(array('code' => 500, 'msg' => '数据错误，请联系管理员处理'));
        }
        $catch = array(
            'gradeId' => $grade['gradeId'],
            'gradeName' => $grade['gradeName'],
            'gradeEndTime' => strtotime($params['gradeEndTime']),
        );
        Db::name('user')->where('userId', '=', $params['userId'])->save($catch);
        return json(array('code' => 200, 'msg' => '开通成功'));
    }

    public function sendDiscounts(){
        $userId = input('userId');

        //查询是否有过期优惠券并改变状态
        $user_coupon = Db::name('user_coupon')->where(['userId'=>$userId,'couponStatus'=>0])->select();
        foreach($user_coupon as $v){
            if(time() >= $v['endTime']){
                Db::name('user_coupon')->where('userCouponId',$v['userCouponId'])->update(['couponStatus'=>'-1']);
            }
        }

        $userInfo = Db::name('user')->where('userId', '=', $userId)->find();
        $this->assign('userInfo', $userInfo);

        $coupon = Db::name('coupon')->where('couponIsDel', '=', '0')->select();
        $this->assign('coupon', $coupon);

        $userCoupon = Db::name('user_coupon')->alias('uc')
            ->join('coupon c', 'uc.couponId = c.couponId')
            ->where('uc.userId', '=', $userId)
            ->field('uc.*,c.*')
            ->order('uc.addTime desc')->select();
        $this->assign('userCoupon', $userCoupon);

        return $this->fetch('send_discounts');
    }

    public function doUserCouponAdd(){
        $params = input('post.');

        if (empty($params['couponId'])) {
            return json(array('code' => 500, 'msg' => '请选择发放的优惠券'));
        }
        $coupon = Db::name('coupon')->where('couponId', '=', $params['couponId'])->find();
        if (empty($coupon)) {
            return json(array('code' => 500, 'msg' => '数据出错，请联系管理员处理'));
        }

        $endTime = 0;
        if ($coupon['validTime'] > 0) {
            $endTime = strtotime(date("Y-m-d",strtotime("+".$coupon['validTime']." day")));
        }
        $catch = array(
            'couponId' => $coupon['couponId'],
            'userId' => $params['userId'],
            'addTime' => strtotime(date('Y-m-d', time())),
            'endTime' => $endTime,
        );
        Db::name('user_coupon')->insertGetId($catch);
        return json(array('code' => 200, 'msg' => '发放成功'));
    }

    public function userCouponDel(){
        $del_id = input('del_id');

        Db::name('user_coupon')->where('userCouponId', '=', $del_id)->delete();
        return json(array('code' => 200, 'msg' => '操作成功'));
    }

    public function userBalanceAdd(){
        $userId = input('userId');

        $userInfo = Db::name('user')->where('userId', '=', $userId)->find();
        $this->assign('userInfo', $userInfo);

        $balanceLog = Db::name('user_balance_log')->where('userId', '=', $userId)->order('addTime desc')->select();
        $this->assign('balanceLog', $balanceLog);

        return $this->fetch('user_balance_add');
    }

    public function doUserBalanceAdd(){
        $params = input('post.');

        if (empty($params['balanceAmount'])) {
            return json(array('code' => 500, 'msg' => '请输入增减的金额'));
        }

        $catch = array(
            'userId' => $params['userId'],
            'balanceAmount' => $params['balanceAmount'],
            'addTime' => time(),
            'balanceNote' => $params['balanceNote'],
            'sourceNote' => '管理员后台操作'
        );
        Db::name('user_balance_log')->insertGetId($catch);

        Db::name('user')->where('userId', '=', $params['userId'])->setInc('userBalance', $params['balanceAmount']);

        Db::name('user_consumption')->insert(array(
            'userId' => $params['userId'],
            'consumptionAmount' => $params['balanceAmount'],
            'addTime' => time(),
            'consumptionNote' => $params['balanceNote'],
            'consumptionType' => 1,
        ));

        return json(array('code' => 200, 'msg' => '操作成功'));
    }

    /**
     * 增减积分
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userIntegralAdd(){

        $userId = input('userId');

        $userInfo = Db::name('user')->where('userId', '=', $userId)->find();
        $this->assign('userInfo', $userInfo);

        $integralLog = Db::name('user_integral_log')->where('userId', '=', $userId)->order('addTime desc')->select();
        $this->assign('integralLog', $integralLog);

        return $this->fetch('user_integral_add');
    }

    public function doUserIntegralAdd(){
        $params = input('post.');

        if (empty($params['integralAmount'])) {
            return json(array('code' => 500, 'msg' => '请输入增减的积分'));
        }

        $catch = array(
            'userId' => $params['userId'],
            'integralAmount' => $params['integralAmount'],
            'addTime' => time(),
            'integralNote' => $params['integralNote'],
            'sourceNote' => '管理员后台操作'
        );
        Db::name('user_integral_log')->insertGetId($catch);

        Db::name('user')->where('userId', '=', $params['userId'])->setInc('userIntegral', $params['integralAmount']);

        return json(array('code' => 200, 'msg' => '操作成功'));
    }

    /**
     * 绑定角色页面
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function bindRoleAdd(){

        $userId = input('userId');
        $data = Db::name('user')->where('userId',$userId)->find();

        $this->assign('userId', $userId);
        $this->assign('data', $data);
        return $this->fetch('bind_role_add');
    }

    /**
     * 绑定教练
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function doBindRoleAdd(){

        $params = input('post.');

        if (empty($params['userId'])) {
            return json(array('code' => 500, 'msg' => '用户id不能为空'));
        }

        $catch = array(
            'role' => $params['role'],
        );

        $data = Db::name('user')->where('userId',$params['userId'])->update($catch);
        if($data){
            return json(array('code' => 200, 'msg' => '操作成功'));
        }else{
            return json(array('code' => 500, 'msg' => '操作失败'));
        }

    }

    /**
     * 绑定销售页面
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function saleAdd(){

        $userId = input('userId');
        $user = Db::name('user')->where('userId',$userId)->find();
        $data = Db::name('user_admin')->where('role',2)->select();

        $this->assign('data', $data);
        $this->assign('user', $user);
        $this->assign('userId', $userId);
        return $this->fetch('sale_add');
    }

    /**
     * 绑定销售
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function dosaleAdd(){

        $params = input('post.');

        if (empty($params['userId'])) {
            return json(array('code' => 500, 'msg' => '用户id不能为空'));
        }

        $catch = array(
            'sale_id' => $params['sale'],
        );

        $data = Db::name('user')->where('userId',$params['userId'])->update($catch);
        if($data){
            return json(array('code' => 200, 'msg' => '操作成功'));
        }else{
            return json(array('code' => 500, 'msg' => '操作失败'));
        }
    }

    /**
     * 发放抵扣券
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function grantVoucher(){

        $userId = input('userId');

        $userInfo = Db::name('user')->where('userId', '=', $userId)->find();
        $this->assign('userInfo', $userInfo);

        $voucher = Db::name('voucher')->select();
        $this->assign('voucher', $voucher);

        $userVoucher = Db::name('user_voucher')->alias('uc')
            ->join('voucher c', 'uc.voucherId = c.voucherId')
            ->where('uc.userId', '=', $userId)
            ->field('uc.*,c.*,uc.addTime as addTimes')
            ->order('uc.addTime desc')->select();
        if($userVoucher){
            foreach($userVoucher as $k=>$v){
                $userVoucher[$k]['statusName']  = $v['status'] == 1?'已使用':'未使用';
            }
        }

        $this->assign('userVoucher', $userVoucher);

        return $this->fetch('grant_voucher');
    }

    /**
     * 发放抵扣券
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function doUserVoucherAdd(){
        $params = input('post.');

        if (empty($params['voucherId'])) {
            return json(array('code' => 500, 'msg' => '请选择发放的抵扣券'));
        }
        $voucher = Db::name('voucher')->where('voucherId', '=', $params['voucherId'])->find();
        if (empty($voucher)) {
            return json(array('code' => 500, 'msg' => '数据出错，请联系管理员处理'));
        }

        $catch = array(
            'voucherId' => $voucher['voucherId'],
            'userId' => $params['userId'],
            'addTime' => strtotime(date('Y-m-d', time())),
        );
        Db::name('user_voucher')->insertGetId($catch);
        return json(array('code' => 200, 'msg' => '发放成功'));
    }

    public function userVoucherDel(){
        $del_id = input('del_id');

        Db::name('user_voucher')->where('userVoucherId', '=', $del_id)->delete();
        return json(array('code' => 200, 'msg' => '操作成功'));
    }

    /**
     * 备注
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function notesAdd(){

        $userId = input('userId');

        $userInfo = Db::name('user')->where('userId', '=', $userId)->find();
        $this->assign('userInfo', $userInfo);
        return $this->fetch('notes_add');
    }

    public function doNotesAdd(){

        $params = input('post.');
        Db::name('user')->where('userId', '=', $params['userId'])->update(['notes'=>$params['notes']]);
        return json(array('code' => 200, 'msg' => '成功'));
    }

    /**
     * 经理/销售列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function user_admin_index(){
        $list = array();
        $keywords = I('keywords/s');
        if(empty($keywords)){
            $res = Db::name('user_admin')->where('status',0)->select();
        }else{
            $res = Db::name('user_admin')->where('user_name|nickname','like','%'.$keywords.'%')->where('status',0)->order('user_admin_id')->select();
        }

        foreach ($res as $val){
            $val['role'] =  $val['role'] == 1?'经理':'销售';
            $val['add_time'] = date('Y-m-d H:i:s',$val['add_time']);
            $list[] = $val;
        }

        $this->assign('list',$list);
        return $this->fetch();
    }

    /**
     * 添加/修改经理和销售
     * @return mixed
     */
    public function user_admin_info(){
        $user_admin_id = I('get.user_admin_id/d',0);
        if($user_admin_id){
            $info = Db::name('user_admin')->where("user_admin_id", $user_admin_id)->find();
            $info['password'] =  "";
            $this->assign('info',$info);
        }
        $act = empty($user_admin_id) ? 'add' : 'edit';
        $this->assign('act',$act);
        return $this->fetch();
    }

    /**
     * 提交经理和销售
     */
    public function adminHandle(){
        $data = I('post.');
        if(empty($data['password'])){
            unset($data['password']);
        }else{
            $data['ec_salt'] = get_rand_str(6,0,1);
            $data['password'] = encrypt($data['password'].$data['ec_salt']);
        }
        if($data['act'] == 'add'){
            unset($data['user_admin_id']);
            $data['add_time'] = time();
            if(Db::name('user_admin')->where("user_name", $data['user_name'])->count()){
                $this->error("此用户名已被注册，请更换",U('User/user_admin_info'));
            }else{
                $r = Db::name('user_admin')->add($data);
            }
        }

        if($data['act'] == 'edit'){
            $r = Db::name('user_admin')->where('user_admin_id', $data['user_admin_id'])->save($data);
        }

        if($data['act'] == 'del' && $data['del_id']>1){
            Db::name('user_admin')->where('user_admin_id', $data['del_id'])->update(['status'=>1]);
            exit(json_encode(1));
        }

        if($r){
            $this->success("操作成功",U('User/user_admin_index'));
        }else{
            $this->error("操作失败",U('User/user_admin_index'));
        }
    }

    /**
     * 删除经理和销售
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function user_admin_del(){

        $data = I('post.');

        $r = Db::name('user_admin')->where('user_admin_id', $data['del_id'])->update(['status'=>1]);
        if($r){
            return json(array('code' => 200, 'msg' => '成功'));
        }else{
            return json(array('code' => 101, 'msg' => '失败'));
        }
    }

    /**
     * 导出
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function export(){

        $params = input('get.');
        $where = array();
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            $where['nickName|userMobile'] = array('like', '%'.$params['keywords'].'%');
        }
        if (isset($params['gradeId']) && $params['gradeId'] != '') {
            $where['gradeId'] = array('=', $params['gradeId']);
        }
        if (isset($params['userStatus']) && $params['userStatus'] != '') {
            $where['userStatus'] = array('=', $params['userStatus']);
        }
        if (isset($params['userRole']) && $params['userRole'] != '') {
            $where['role'] = array('=', $params['userRole']);
        }
        $list = Db::name('user')->where($where)->order('addTime desc')->select();
        if($list){
            foreach($list as $k=>$v){
                $list[$k]['addTime'] = date('Y-m-d',$v['addTime']);
                $list[$k]['sale_name'] = Db::name('user_admin')->where('user_admin_id',$v['sale_id'])->value('nickname');
            }
        }
        $filename='用户列表';
        $field = array(
            'A' => array('userId', '序号'),
            'B' => array('nickName', '昵称'),
            'C' => array('userMobile', '手机号码'),
            'D' => array('gradeName', '会员等级'),
            'E' => array('notes', '备注'),
            'F' => array('userBalance', '余额'),
            'G' => array('userIntegral', '积分'),
            'H' => array('sale_name', '顾问'),
            'I' => array('addTime', '注册时间'),
        );

        $this->phpExcelList($field,$list,$filename);

    }

    /**
     * 直接导出需要生产的内容
     * @param $field
     * @param $list
     * @param string $title
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function phpExcelList($field, $list, $filename='文件')
    {
        vendor("PHPExcel.PHPExcel");
        $objPHPExcel = new \PHPExcel();
        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel); //设置保存版本格式
        foreach ($list as $key => $value) {
            foreach ($field as $k => $v) {
                if ($key == 0) {
                    $objPHPExcel->getActiveSheet()->setCellValue($k . '1', $v[1]);
                }
                $i = $key + 2; //表格是从2开始的
                $objPHPExcel->getActiveSheet()->setCellValue($k . $i, $value[$v[0]]);
            }
        }
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename='.$filename.'.xls');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }

}